<template>
  <div class="scheme-detail-index sub-margin">
    <div class="sub-page-title">考核方案管理</div>
    <div class="return-box">
      <el-button size="small" icon="el-icon-arrow-left" @click.stop="returnOrg">返回</el-button>
      <el-button
        v-if="!editing"
        type="primary"
        size="small"
        icon="el-icon-edit-outline"
        :disabled="statusTag[schemeInfo.examineStatus] !== 'unPub'"
        @click.stop="onEdit">
        编辑
      </el-button>
      <template v-else>
        <el-button type="primary" size="small" icon="el-icon-check" @click.stop="onSave">保存</el-button>
        <el-button size="small" icon="el-icon-close" @click.stop="onCancel">取消</el-button>
      </template>
    </div>
    <div class="content">
      <h3 class="title">{{ schemeInfo.title || '' }}</h3>
      <el-scrollbar class="scroll-content">
        <div class="detail-content">
          <el-descriptions class="detail-content-desc" title="考核方案详情" :column="3" size="medium" border>
            <!-- 第一行：考核名称 -->
            <el-descriptions-item label="考核名称" :span="3">
              <template v-if="editing">
                <div class="form-item" :class="{ 'error-form-item': !schemeForm.title }">
                  <el-input
                    v-model.trim="schemeForm.title"
                    size="medium"
                    autocomplete="off"
                    :maxlength="50"
                    show-word-limit
                    clearable
                    placeholder="请输入考核名称"></el-input>
                  <div class="empty-tips" v-if="!schemeForm.title">考核名称不能为空</div>
                </div>
              </template>
              <template v-else>
                {{ schemeInfo.title || '' }}
              </template>
            </el-descriptions-item>
            <!-- 第二行：考核描述 -->
            <el-descriptions-item label="考核描述" :span="3">
              <template v-if="editing">
                <el-input
                  v-model.trim="schemeForm.reportExplain"
                  type="textarea"
                  size="medium"
                  autocomplete="off"
                  :autosize="{ minRows: 2, maxRows: 6 }"
                  :maxlength="500"
                  show-word-limit
                  :clearable="true"
                  placeholder="请输入考核说明"></el-input>
              </template>
              <template v-else>
                {{ schemeInfo.reportExplain || '' }}
              </template>
            </el-descriptions-item>
            <!-- 第三行：考核状态及考核周期 -->
            <el-descriptions-item label="考核状态" :span="1">
              {{ schemeStatus[schemeInfo.examineStatus] }}
            </el-descriptions-item>
            <el-descriptions-item label="考核周期" :span="2">
              {{ schemeInfo.year + '年' || '' }}
            </el-descriptions-item>
            <!-- 第四行：方案创建人及创建时间 -->
            <el-descriptions-item label="考核方案创建人" :span="1">
              {{ schemeInfo.userName }}
            </el-descriptions-item>
            <el-descriptions-item label="考核方案创建时间" :span="2">
              {{ schemeInfo.createTime | filterDate }}
            </el-descriptions-item>
            <!-- 第五行：考核单位 -->
            <el-descriptions-item label="考核单位" :span="3">
              <el-tag type="success" v-for="org in orgList" :key="org.id">{{ org.name }}</el-tag>
            </el-descriptions-item>
            <!-- 第六行：涉密单位 -->
            <el-descriptions-item label="涉密单位" :span="3">
              <el-tag type="danger" v-for="org in secretOrgList" :key="org.id">{{ org.name }}</el-tag>
            </el-descriptions-item>
            <!-- 第七行：考核类型及考核模板 -->
            <el-descriptions-item label="考核类型" :span="1">{{ schemeInfo.type | filterType }}</el-descriptions-item>
            <el-descriptions-item label="考核模板" :span="2">{{ modelName }}</el-descriptions-item>
            <!-- 第八行：共享指标填报人员 -->
            <el-descriptions-item label="共享指标填报人员" :span="3">
              <template v-if="scoreUser.length">
                <el-tag type="info" v-for="user in shareUser" :key="user.id">{{ user.userName }}</el-tag>
              </template>
            </el-descriptions-item>
            <!-- 第九行：指标撤回修改时间段 -->
            <el-descriptions-item label="指标撤回修改时间段" :span="3">
              <template v-if="editing">
                <el-date-picker
                  v-model="recallTime"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  size="medium"
                  value-format="yyyy-MM-dd"
                  format="yyyy-MM-dd"></el-date-picker>
              </template>
              <template v-else>
                {{ editTime }}
              </template>
            </el-descriptions-item>
            <!-- 第十行： 考核分数校准人员-->
            <el-descriptions-item label="考核分数校准人员" :span="3">
              <template v-if="scoreUser.length">
                <el-tag type="info" v-for="user in scoreUser" :key="user.id">{{ user.userName }}</el-tag>
              </template>
            </el-descriptions-item>
            <!-- 第十一行： 1级审核人员 -->
            <el-descriptions-item label="报告编辑1级审核人员" :span="3">
              <template v-if="level1User.length">
                <el-tag type="info" v-for="user in level1User" :key="user.id">{{ user.userName }}</el-tag>
              </template>
            </el-descriptions-item>
            <!-- 第十二行： 2级审核人员 -->
            <el-descriptions-item label="报告编辑2级审核人员" :span="3">
              <template v-if="level2User.length">
                <el-tag type="info" v-for="user in level2User" :key="user.id">{{ user.userName }}</el-tag>
              </template>
            </el-descriptions-item>
            <!-- 第十三行： 3级审核人员 -->
            <!-- <el-descriptions-item label="报告编辑3级审核人员" :span="3">
              <template v-if="level3User.length">
                <el-tag type="info" v-for="user in level3User" :key="user.id">{{ user.userName }}</el-tag>
              </template>
            </el-descriptions-item> -->
          </el-descriptions>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>
<script>
import { getReportCfg, saveReportCfg } from '@apis/indScheme.js'
import { listModel } from '@apis/indModel.js'
import { listRecursiveOrgan } from '@api/modules/system.js'
import { formatDate } from '@utility/utility'
import { IND_STEP_STATUS } from '@utility/dict'
import { cloneDeep } from 'lodash'

export default {
  name: 'schemeDetail',
  data() {
    return {
      schemeId: '',
      schemeStatus: IND_STEP_STATUS._label,
      statusTag: IND_STEP_STATUS._tag,
      editing: false, // 是否处于编辑状态
      schemeInfo: {},
      schemeForm: {}, // 编辑时使用的数据
      recallTime: [],
      cycleList: [],
      flatUnits: [],
      modelList: [],
      editTime: '',
      shareUser: [],
      scoreUser: [],
      level1User: [],
      level2User: [],
      level3User: [],
      requiredFields: ['title'], // 可编辑的必填项
    }
  },
  filters: {
    filterType(type) {
      if (!type || type === '1') {
        return '履职效果考核'
      } else {
        return '履职能力考核'
      }
    },
    filterDate(val) {
      if (val) {
        return formatDate(new Date(val).toLocaleString(), 'yyyy-MM-dd hh:mm:ss')
      }
      return '-'
    },
  },
  computed: {
    orgList() {
      const orgList = []
      const { reviewOrgList = [] } = this.schemeInfo || {}
      if (this.flatUnits.length && reviewOrgList.length) {
        for (let i = 0; i < reviewOrgList.length; i++) {
          for (let j = 0; j < this.flatUnits.length; j++) {
            const curOrg = this.flatUnits[j]
            if (curOrg.id === reviewOrgList[i].orgId) {
              orgList.push({
                id: reviewOrgList[i].orgId,
                isSecret: reviewOrgList[i].isSecret,
                name: curOrg.orgName,
              })
              break
            }
          }
        }
      }
      console.log(orgList)
      return orgList
    },
    secretOrgList() {
      let secretOrgList = []
      if (this.orgList.length) {
        secretOrgList = this.orgList.filter(item => item.isSecret === '1')
      }
      return secretOrgList
    },
    modelName() {
      let modelName = ''
      if (this.modelList.length) {
        modelName = this.modelList[0].modelName
      }
      return modelName
    },
  },
  created() {
    const { id = '' } = this.$route.query || {}
    this.schemeId = id
    this.getSchemeDetail()
    this.initData()
  },
  methods: {
    // 获取考核周期
    getCycleList() {
      const curYear = new Date().getFullYear()
      const nextYear = curYear + 1
      this.cycleList = [
        { name: `${curYear}年年度`, code: curYear + '' },
        { name: `${nextYear}年年度`, code: nextYear + '' },
      ]
    },
    // 获取机构树
    async initData() {
      const { status, data } = await listRecursiveOrgan()
      if (status === 200 && data && data.length) {
        this.flatUnits = this.treeToArr(data, [])
      } else {
        this.unitList = []
      }
    },
    // 树状机构平铺
    treeToArr(data, res = []) {
      if (data && data.length) {
        let curInx = 0
        data.forEach((item, inx) => {
          curInx = inx
          item.isLeaf = !(item.queryOutVOS && item.queryOutVOS.length > 0)
          res.push(item)
          if (item.queryOutVOS && item.queryOutVOS.length) {
            this.treeToArr(item.queryOutVOS, res)
          }
        })
        if (curInx === data.length - 1 && data[0].pid === '-1') {
          return res
        }
      }
    },
    async getSchemeDetail() {
      if (!this.schemeId) {
        return false
      }
      const { code, data } = await getReportCfg(this.schemeId)
      if (code === 0 && data && data.id) {
        this.schemeInfo = data || {}
        this.getEditTime([data.recallStart || '', data.recallEnd || ''])
        this.getUserList(data.reviewProcessList || [])
        this.getModelList(data.type)
      }
    },
    getEditTime(timeRange) {
      let time = ''
      if (timeRange[0] && timeRange[1]) {
        time = formatDate(new Date(timeRange[0]), 'yyyy-MM-dd')
        time += ' ～ '
        time += formatDate(new Date(timeRange[1]), 'yyyy-MM-dd')
      }
      this.editTime = time
    },
    getUserList(list) {
      if (list.length) {
        const shareUser = []
        const scoreUser = []
        const level1User = []
        const level2User = []
        const level3User = []
        list.forEach(item => {
          if (item.reviewType === '1-1') {
            shareUser.push(item)
          } else if (item.reviewType === '1-2') {
            scoreUser.push(item)
          } else if (item.reviewType === '1-3') {
            if (String(item.grade) === '1') {
              level1User.push(item)
            } else if (String(item.grade) === '2') {
              level2User.push(item)
            } else {
              level3User.push(item)
            }
          }
        })
        this.shareUser = shareUser
        this.scoreUser = scoreUser
        this.level1User = level1User
        this.level2User = level2User
        this.level3User = level3User
      }
    },
    // 获取考核模板
    async getModelList(type) {
      const params = {
        id: this.schemeInfo.modelId,
        modelName: '',
        status: '',
        type,
      }
      if (!params.id) {
        delete params.id
      }
      const { code, data } = await listModel(params, 1, 10)
      if (code === 0 && data && data.content) {
        this.modelList = data.content
      } else {
        this.modelList = []
      }
    },
    // 返回方案列表页
    returnOrg() {
      this.$router.push({
        name: 'JXGL_ASSESS_MANAGE',
      })
    },
    // 启动编辑
    onEdit() {
      this.schemeForm = cloneDeep(this.schemeInfo)
      const { recallStart, recallEnd } = this.schemeForm
      if (recallStart || recallEnd) {
        this.recallTime = [recallStart, recallEnd]
      } else {
        this.recallTime = []
      }
      this.editing = true
    },
    // 取消编辑
    onCancel() {
      this.editing = false
      this.schemeForm = {}
    },
    // 保存更改
    onSave() {
      let flag = true
      this.requiredFields.forEach(item => {
        if (!this.schemeForm[item]) {
          flag = false
        }
      })
      // 有必填项为空
      if (!flag) {
        return false
      }
      this.onSchemeUpdate()
    },
    async onSchemeUpdate() {
      const params = this.buildParams()
      const { code } = await saveReportCfg(params)
      if (code === 0) {
        this.getSchemeDetail()
        this.$message.success('编辑成功')
      }
    },
    // 构建参数
    buildParams() {
      const params = cloneDeep(this.schemeForm)
      // 获取填报撤回时间段
      if (this.recallTime.length) {
        params.recallStart = this.recallTime[0]
        params.recallEnd = this.recallTime[1]
      } else {
        params.recallStart = ''
        params.recallEnd = ''
      }
      params.status = this.schemeForm.examineStatus

      // 删除不必要的字段
      delete params.userName
      delete params.createBy
      delete params.createTime
      delete params.examineStatus

      return params
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@styles/layout.scss';

.scheme-detail-index {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  .return-box {
    margin-top: 20px;
    text-align: left;
  }
  .content {
    flex: 1;
    padding: 20px 0;
    margin-top: 20px;
    .title {
      font-size: 18px;
      line-height: 28px;
      margin-bottom: 20px;
      color: #333;
      font-weight: 600;
      text-align: center;
    }

    .scroll-content {
      height: calc(100vh - 240px);
      width: 100%;
    }

    .detail-content {
      min-width: 640px;
      max-width: 1000px;
      margin: 0 auto;
      display: flex;
      flex-direction: column;
      align-items: center;
      &-desc {
        width: 100%;
      }
      ::v-deep .el-descriptions-item__label {
        min-width: 160px;
      }
      ::v-deep .el-descriptions-item__content {
        .el-tag {
          margin: 5px 0;
        }
        .el-tag + .el-tag {
          margin-left: 10px;
        }
        .form-item {
          &.error-form-item {
            input {
              border-color: #f56c6c;
            }
            .empty-tips {
              position: relative;
              top: 2px;
              font-size: 12px;
              line-height: 1;
              color: #f56c6c;
            }
          }
        }
      }
    }
  }
}
</style>
